//
//  WDSplashManager.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/5/30.
//

#import "WDSplashManager.h"
#import "WDAdStatusManager.h"
#import "WDBMSModel.h"
#import "WDCallBackManager.h"
#import "WDKeychain.h"
#import "WDADManager.h"
@interface WDSplashManager ()
@property(nonatomic, strong) GADAppOpenAd *openAd;
@property (nonatomic, assign) BOOL hasShowAd;
@end

@implementation WDSplashManager

static WDSplashManager *_splash = nil;
+ (instancetype)shareSplash{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _splash = [[self alloc] init];
        _splash.splashIDIndex = 0;
    });
    return _splash;
}

- (BOOL)wasLoadTimeLessThanNHoursAgo:(int)n {
  NSDate *now = [NSDate date];
  NSTimeInterval timeIntervalBetweenNowAndLoadTime = [now timeIntervalSinceDate:self.loadTime];
  double secondsPerHour = 3600.0;
  double intervalInHours = timeIntervalBetweenNowAndLoadTime / secondsPerHour;
  return intervalInHours < n;
}

- (NSString *)getAdUnitID
{
    if ([WDBMSModel shareBMSModel].splashID.count > 0)
    {
        if (self.splashIDIndex > [WDBMSModel shareBMSModel].splashID.count)
        {
            self.splashIDIndex = 0;
        }
        NSArray *temp = [WDBMSModel shareBMSModel].splashID[self.splashIDIndex];
        NSString *sid = temp[1];
        self.splashIDIndex++;
        if (sid)
        {
            return sid;
        }
    }
    return @"";
}

- (void)requestAppOpenAd {
    WDLog(@"requestAppOpenAd111");
    WDLog(@"requestAppOpenAd");
//    NSString *sid = @"ca-app-pub-3940256099942544/5662855259";
    NSString *sid = [self getAdUnitID];
    if (sid.length <= 0)
    {
        WDLog(@"splash id:%@",sid);
        return;
    }
    WDLog(@"splash id:%@",sid);
    
    __weak WDSplashManager *weakSelf = self;
    
    dispatch_async ( dispatch_get_main_queue (), ^{
        UIInterfaceOrientation orientation = [ UIApplication sharedApplication ].statusBarOrientation ;
        
        [[WDAdStatusManager shareStatusManager] adLoadWithEventName:SPLASH_EVENT_NAME];
        
//        [GADAppOpenAd loadWithAdUnitID:sid request:[GADRequest request] completionHandler:^(GADAppOpenAd * _Nullable appOpenAd, NSError * _Nullable error) {
//            
//        }];
        
        [GADAppOpenAd loadWithAdUnitID:sid
                               request:[GADRequest request]
                     completionHandler:^(GADAppOpenAd *_Nullable appOpenAd, NSError *_Nullable error) {
            if (error) {
                WDLog(@"Failed to load app open ad: %@,==:%@,==:%@", error,error.localizedDescription,error.localizedFailureReason);
                self.isLoadSplash = NO;
                [[WDAdStatusManager shareStatusManager] adLoadFailedWithCode:error.code message:error.localizedDescription eventName:SPLASH_EVENT_NAME];
                [[WDAdStatusManager shareStatusManager] adLoadFillFailedWithEventName:SPLASH_EVENT_NAME];
                
                [self reLoad];
                
                return;
            }
            
            self.openAd = appOpenAd;
            appOpenAd.paidEventHandler = ^(GADAdValue * _Nonnull value) {
                WDSplashManager *strongSelf = weakSelf;
                NSDecimalNumber *value1 = value.value;
                NSString *currencyCode = value.currencyCode;
                GADAdValuePrecision precision = value.precision;
                
                
                WDLog(@"paidEventHandler value1:%@,currencyCode:%@,precision:%ld",value1,currencyCode,(long)precision);
                
                // Get the ad unit ID.
//                NSString *adUnitId = strongSelf.openAd.adUnitID;
                
                GADAdNetworkResponseInfo *loadedAdNetworkResponseInfo = strongSelf.openAd.responseInfo.loadedAdNetworkResponseInfo;
                NSString *adSourceName = loadedAdNetworkResponseInfo.adSourceName;
                NSString *adSourceID = loadedAdNetworkResponseInfo.adSourceID;
                NSString *adSourceInstanceName = loadedAdNetworkResponseInfo.adSourceInstanceName;
                NSString *adSourceInstanceID = loadedAdNetworkResponseInfo.adSourceInstanceID;
                NSDictionary<NSString *, id> *extras = strongSelf.openAd.responseInfo.extrasDictionary;
                
                [[WDAdStatusManager shareStatusManager] adRevenue:@"splash" source:@"admob" revenue:[NSString stringWithFormat:@"%@",value.value] currency:currencyCode];
                
                WDLog(@"paidEventHandler2 adSourceName:%@,adSourceID:%@,adSourceInstanceName:%@,adSourceInstanceID:%@,extras:%@",adSourceName,adSourceID,adSourceInstanceName,adSourceInstanceID,extras);
                
            };
            
            [[WDAdStatusManager shareStatusManager] adLoadFillSuccessWithEventName:SPLASH_EVENT_NAME];
            self.isLoadSplash = YES;
            self.appOpenAd = appOpenAd;
            self.appOpenAd.fullScreenContentDelegate = self;
            self.loadTime = [NSDate date];
            if (self.delegate && [self.delegate performSelector:@selector(adLoadedSuccessfully)]){
                [self.delegate adLoadedSuccessfully];
            }
            if (self.hasShowAd)
            {
                self.hasShowAd = NO;
                [self tryToPresentAd];
            }
        }];
    });
}

- (void)reLoad
{
    double delayInSeconds = 5.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self requestAppOpenAd];
    });
}

- (void)tryToPresentAd {
    
    NSString *status = [WDKeychain WDKeychainGetSplashOpenStatus];
    if ([status isEqualToString:@"1"])
    {
        //去除了splash ad
        return;
    }
    [WDADManager shareADManager].WDADShowStats = ADShowing;
    [[WDAdStatusManager shareStatusManager] adShowWithEventName:SPLASH_EVENT_NAME];
    if (self.appOpenAd && [self wasLoadTimeLessThanNHoursAgo:4]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIViewController *rootController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
            [self.appOpenAd presentFromRootViewController:rootController];
        });
        
    } else {
        self.hasShowAd = YES;
        // If you don't have an ad ready, request one.
        [self reLoad];
    }
}

#pragma mark - GADFullScreenContentDelegate
/// Tells the delegate that the ad failed to present full screen content.
- (void)ad:(nonnull id<GADFullScreenPresentingAd>)ad
didFailToPresentFullScreenContentWithError:(nonnull NSError *)error {
    WDLog(@"didFailToPresentFullScreenContentWithError:%@,%@",error.localizedDescription,error.localizedFailureReason);
    
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:ShowFail adSpace:[WDCallBackModel shareCallBackModel].adSpace message:error.localizedDescription];
    self.isLoadSplash = NO; 
    [[WDAdStatusManager shareStatusManager] adShowFailedWithCode:error.code message:error.localizedDescription eventName:SPLASH_EVENT_NAME];
    [self reLoad];
    
}

/// Tells the delegate that the ad will present full screen content.
- (void)adWillPresentFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:Show adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@""];
    [[WDAdStatusManager shareStatusManager] adCompletedWithEventName:SPLASH_EVENT_NAME];
    WDLog(@"adWillPresentFullScreenContent");
}

/// Tells the delegate that the ad will dismiss full screen content.
- (void)adWillDismissFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad
{
    
}

/// Tells the delegate that the ad dismissed full screen content.
- (void)adDidDismissFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {
    WDLog(@"adDidDismissFullScreenContent");
    
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:Finish adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@""];
    self.hasShowAd = NO;
    self.isLoadSplash = NO;
    [[WDAdStatusManager shareStatusManager] adCloseWithEventName:SPLASH_EVENT_NAME];
    [self requestAppOpenAd];
}

- (void)adDidRecordClick:(nonnull id<GADFullScreenPresentingAd>)ad
{
    [[WDAdStatusManager shareStatusManager] adClickWithEventName:SPLASH_EVENT_NAME];
    WDLog(@"adDidRecordClick");
}

@end
